#include "cmsis_os2.h"
#include <stdio.h>
#include <string.h>

/* 互斥锁对象 */
osMutexId_t g_testMux;
/* 任务ID */
osThreadId_t g_testTaskId01;
osThreadId_t g_testTaskId02;

/* 定义任务函数 */
void Example_MutexTask1(void *argument)
{
    osStatus_t status;

    printf("task1 try to get mutex, wait 10 ticks.\n");
    status = osMutexAcquire(g_testMux, 10);  // 10 ticks (may be ms depending on config)

    if (status == osOK) {
        printf("task1 get mutex g_testMux.\n");
        osMutexRelease(g_testMux);
        return;
    } else if (status == osErrorTimeout) {
        printf("task1 timeout and try to get mutex, wait forever.\n");
        status = osMutexAcquire(g_testMux, osWaitForever);
        if (status == osOK) {
            printf("task1 wait forever, get mutex g_testMux.\n");
            osMutexRelease(g_testMux);
            return;
        }
    }
    return;
}

void Example_MutexTask2(void *argument)
{
    printf("task2 try to get mutex, wait forever.\n");
    osMutexAcquire(g_testMux, osWaitForever);

    printf("task2 get mutex g_testMux and suspend 100 ticks.\n");
    osDelay(100);  // delay 100 ticks/ms

    printf("task2 resumed and post the g_testMux\n");
    osMutexRelease(g_testMux);
    return;
}

int main(void)
{
    osStatus_t status;

    osKernelInitialize(); // 初始化CMSIS-RTOS

    // 创建互斥锁
    const osMutexAttr_t mutexAttr = {
        .name = "TestMutex"
    };
    g_testMux = osMutexNew(&mutexAttr);
    if (g_testMux == NULL) {
        printf("Mutex creation failed.\n");
        return -1;
    }

    // 创建任务1
    g_testTaskId01 = osThreadNew(Example_MutexTask1, NULL, 
                                 &(osThreadAttr_t){
                                     .name = "MutexTsk1",
                                     .priority = osPriorityNormal
                                 });

    if (g_testTaskId01 == NULL) {
        printf("task1 create failed.\n");
        return -1;
    }

    // 创建任务2
    g_testTaskId02 = osThreadNew(Example_MutexTask2, NULL,
                                 &(osThreadAttr_t){
                                     .name = "MutexTsk2",
                                     .priority = osPriorityBelowNormal
                                 });

    if (g_testTaskId02 == NULL) {
        printf("task2 create failed.\n");
        return -1;
    }

    osKernelStart(); // 启动RTOS调度器

    return 0;
}
